<template>
  <div id="EquipmentManagePage">
    <div class="search-wrapper">
      <div class="title-wrapper">
        <span class="title">设备筛选</span>
      </div>
      <div class="content-wrapper">
        <div class="search-item">
          <span class="item-label">设备名称</span>
          <el-input
            class="item-input"
            v-model="queryObj.keyword"
            placeholder="请输入设备名称"
            clearable
            @change="searchHandle"
          />
        </div>
        <div class="search-item">
          <span class="item-label">设备类型</span>
          <el-select
            class="item-input"
            v-model="queryObj.typeId"
            placeholder="请选择设备类型"
            clearable
            @change="searchHandle"
          >
            <el-option label="所有" :value="''" />
            <el-option
              v-for="item in equipmentTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </div>
        <div class="search-item">
          <span class="item-label">设备状态</span>
          <el-select
            class="item-input"
            v-model="queryObj.status"
            placeholder="请选择设备状态"
            clearable
            @change="searchHandle"
          >
            <el-option label="所有" :value="''" />
            <el-option label="空闲中" :value="'IDLE'" />
            <!-- <el-option label="预约中" :value="'RESERVEING'" /> -->
            <el-option label="使用中" :value="'IN_USE'" />
            <!-- <el-option label="维护中" :value="'REPAIRING'" /> -->
            <el-option label="损坏" :value="'DAMAGED'" />
            <el-option label="报废" :value="'SCRAPPED'" />
          </el-select>
        </div>
        <div class="search-btn" @click="searchHandle">筛选</div>
        <div class="add-btn-wrapper">
          <div class="add-btn" @click="addHandle">新增</div>
          <div class="batch-import-btn" @click="batchImportHandle">
            批量导入
          </div>
          <div class="download-template-btn" @click="downloadTemplateHandle">
            下载模板
          </div>
          <div class="backup-btn" @click="backupHandle">一键备份</div>
        </div>
      </div>
    </div>
    <div class="data-wrapper">
      <div class="title-wrapper">
        <span class="title">设备列表</span>
      </div>
      <div class="table-wrapper">
        <el-table
          :data="tableData"
          stripe
          fit
          class="self-stripe-table"
          height="100%"
        >
          <el-table-column type="index" label="序号" width="100" />
          <el-table-column prop="name" label="设备名称">
            <template #default="scope">
              <div class="equipment-name-wrapper">
                <img
                  :src="
                    (scope.row.photoList && scope.row.photoList[0]?.url) ||
                    require('@/assets/images/defaultDevice.png')
                  "
                  alt="设备图片"
                  class="equipment-photo"
                />
                <div class="equipment-info-wrapper">
                  <span class="equipment-name">
                    {{ scope.row.name }}
                  </span>

                  <span class="equipment-sn"> SN：{{ scope.row.code }} </span>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="设备类型">
            <template #default="scope">
              <div>{{ scope.row.typeInfo?.name || "--" }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="model" label="设备型号" />
          <el-table-column label="设备负责人">
            <template #default="scope">
              <div>{{ scope.row.chargeUserInfo?.name || "--" }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="设备状态">
            <template #default="scope">
              <div class="signal-status" :class="scope.row.status">
                {{ statusMap[scope.row.status] }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="left" width="250">
            <template #default="scope">
              <div class="table-btn" @click="editHandle(scope.row)">查看</div>
              <div
                class="table-btn"
                @click="updateDeviceStatusHandle(scope.row)"
              >
                更改状态
              </div>
              <div class="table-btn" @click="deleteHandle(scope.row)">删除</div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="pagination.totalPages > 1" class="pagination-wrapper">
      <el-pagination
        v-model="pagination.page"
        :total="pagination.totalElements"
        :page-size="pagination.size"
        background
        :hide-on-single-page="true"
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
      />
    </div>

    <!-- 添加资源弹框 -->
    <el-dialog
      class="self-dialog"
      v-model="addDialogVisible"
      title="添加设备"
      width="50%"
      @close="resetAddForm"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="设备名称" prop="name">
          <el-input
            v-model="addForm.name"
            placeholder="请输入设备名称"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="设备类型" prop="typeId">
          <el-select v-model="addForm.typeId" placeholder="请选择设备类型">
            <el-option
              v-for="item in equipmentTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="序列号" prop="code">
          <el-input
            v-model="addForm.code"
            placeholder="请输入设备序列号"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="型号" prop="model">
          <el-input v-model="addForm.model" placeholder="请输入设备型号" />
        </el-form-item>
        <el-form-item label="负责人" prop="responsiblePerson">
          <el-select
            v-model="addForm.chargeUserCode"
            placeholder="请选择负责人"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.name"
              :value="item.userCode"
              filterable
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备状态" prop="status">
          <el-select v-model="addForm.status" placeholder="请选择设备状态">
            <el-option label="空闲中" :value="'IDLE'" />
            <!-- <el-option label="预约中" :value="'RESERVEING'" /> -->
            <el-option label="使用中" :value="'IN_USE'" />
            <!-- <el-option label="维护中" :value="'REPAIRING'" /> -->
            <el-option label="损坏" :value="'DAMAGED'" />
            <el-option label="报废" :value="'SCRAPPED'" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备位置" prop="location">
          <el-input
            v-model="addForm.location"
            placeholder="请输入设备位置"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="设备归属" prop="belong">
          <el-select v-model="addForm.belong" placeholder="请选择设备归属">
            <el-option
              v-for="item in ogaList"
              :key="item.id"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="采购时间" prop="procurementTime">
          <el-date-picker
            v-model="addForm.purchaseDate"
            type="date"
            format="YYYY/MM/DD"
            value-format="x"
            placeholder="请选择采购时间"
            style="width: 100%"
            :disabledDate="disableFutureDates"
          />
        </el-form-item>
        <el-form-item label="投运时间" prop="operationalTime">
          <el-date-picker
            v-model="addForm.deliveryDate"
            type="date"
            format="YYYY/MM/DD"
            value-format="x"
            placeholder="请选择投运时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="采购价格" prop="purchasePrice">
          <el-input
            v-model="addForm.purchasePrice"
            placeholder="请输入设备价值（元）"
            style="width: 80%"
          />（元）
        </el-form-item>
        <el-form-item label="使用年限" prop="useYears">
          <el-input-number
            v-model="addForm.useYears"
            :min="1"
            :max="100"
            :step="1"
            placeholder="请输入设备使用年限（年）"
            style="width: 80%"
            controls-position="right"
          />（年）
        </el-form-item>
        <el-form-item label="备注1" prop="note1">
          <el-input
            v-model="addForm.description1"
            placeholder="请输入设备备注1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注2" prop="note2">
          <el-input
            v-model="addForm.description2"
            placeholder="请输入设备备注2"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitAddForm"
            :loading="addFormLoading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量导入弹框 -->
    <el-dialog
      class="self-dialog"
      v-model="batchImportDialogVisible"
      title="批量导入设备"
      width="40%"
      @close="resetBatchImportForm"
    >
      <div class="batch-import-content">
        <div class="import-tips">
          <p>请按照模板格式填写设备信息，支持.xlsx格式文件</p>
          <p>文件大小不超过100MB</p>
        </div>

        <el-form
          ref="batchImportFormRef"
          :model="batchImportForm"
          :rules="batchImportFormRules"
          label-width="100px"
          label-position="right"
        >
          <el-form-item label="选择文件" prop="file">
            <el-upload
              ref="uploadRef"
              class="upload-demo"
              :auto-upload="false"
              :show-file-list="true"
              :limit="1"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              :before-upload="beforeFileUpload"
              accept=".xlsx,.xls"
              drag
            >
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  只能上传 xlsx/xls 文件，且不超过 10MB
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>

        <!-- 导入进度 -->
        <div v-if="importProgress.show" class="import-progress">
          <el-progress
            :percentage="importProgress.percentage"
            :status="importProgress.status"
            :stroke-width="8"
          />
          <div class="progress-text">{{ importProgress.text }}</div>
        </div>

        <!-- 导入结果 -->
        <div v-if="importResult.show" class="import-result">
          <div class="result-title">导入结果</div>
          <div class="result-content">
            <div class="result-item success">
              <span class="label">成功：</span>
              <span class="value">{{ importResult.successCount }}条</span>
            </div>
            <div class="result-item error">
              <span class="label">失败：</span>
              <span class="value">{{ importResult.failCount }}条</span>
            </div>
          </div>
          <div
            v-if="
              importResult.failureRecords &&
              importResult.failureRecords.length > 0
            "
            class="error-list"
          >
            <div class="error-title">错误详情：</div>
            <div
              class="error-item"
              v-for="(error, index) in importResult.failureRecords"
              :key="index"
            >
              <span class="error-row">第{{ error.rowIndex }}行-</span>
              <span class="error-name">{{ error.deviceName }}：</span>
              <span class="error-message">{{ error.failureReason }}</span>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchImportDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitBatchImport"
            :loading="batchImportLoading"
            :disabled="!batchImportForm.file"
          >
            开始导入
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改设备状态弹框 -->
    <el-dialog
      class="self-dialog"
      v-model="updateDeviceStatusDialogVisible"
      title="修改设备状态"
      width="50%"
    >
      <el-form
        ref="updateDeviceStatusFormRef"
        :model="updateDeviceStatusForm"
        :rules="updateDeviceStatusFormRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="设备状态" prop="status">
          <el-select
            v-model="updateDeviceStatusForm.status"
            placeholder="请选择设备状态"
          >
            <el-option label="空闲中" value="IDLE" />
            <!-- <el-option label="预约中" value="RESERVEING" /> -->
            <el-option label="使用中" value="IN_USE" />
            <!-- <el-option label="维护中" value="REPAIRING" /> -->
            <el-option label="损坏" value="DAMAGED" />
            <el-option label="报废" value="SCRAPPED" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="updateDeviceStatusDialogVisible = false"
            >取消</el-button
          >
          <el-button
            type="primary"
            @click="submitUpdateDeviceStatusForm"
            :loading="updateDeviceStatusFormLoading"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { UploadFilled } from "@element-plus/icons-vue";
import axios from "axios";
import { ListResponseType, PaginationType } from "@/api/globalType";
import {
  getEquipmentListAPI,
  addOrUpdateEquipmentAPI,
  typesAPI,
  batchImportEquipmentAPI,
  deleteEquipmentAPI,
  updateDeviceStatusAPI,
  backupDatabaseAPI,
} from "@/api/service/equipmentManage";
import {
  EquipmentType,
  AddOrUpdateEquipmentQueryType,
  EquipmentStatus,
} from "@/api/types/equipment";
import { getUserListAPI, GetUserListType, UserType } from "@/api/service/user";
import { getOgaListAPI, OgaType } from "@/api/service/oga";

const router = useRouter();

const statusMap = ref<Record<string, string>>({
  IDLE: "空闲中",
  IN_USE: "使用中",
  DAMAGED: "损坏",
  SCRAPPED: "报废",
});

// 查询条件
const queryObj = ref({
  keyword: "",
  typeId: "",
  status: "",
  belong: "",
});

// 分页
const pagination = ref<PaginationType>({
  page: 1,
  size: 50,
  totalElements: 0,
  totalPages: 0,
});

// 表格数据
const tableData = ref<EquipmentType[]>([]);

// API调用保护状态
const listApiLoading = ref(false);

function getEquipmentList() {
  // 防止并发调用
  if (listApiLoading.value) return;

  listApiLoading.value = true;

  getEquipmentListAPI({
    keyword: queryObj.value.keyword,
    typeId: queryObj.value.typeId,
    status: queryObj.value.status as EquipmentStatus,
    belong: queryObj.value.belong,
    page: pagination.value.page,
    size: pagination.value.size,
  })
    .then((_data: any) => {
      const data = _data as ListResponseType<EquipmentType>;
      nextTick(() => {
        tableData.value = data.content;
        pagination.value.page = data.page;
        pagination.value.size = data.size;
        pagination.value.totalElements = data.totalElements;
        pagination.value.totalPages = data.totalPages;
      });
    })
    .catch(() => {
      ElMessage.error("获取设备列表失败");
    })
    .finally(() => {
      listApiLoading.value = false;
    });
}
getEquipmentList();

// 筛选
function searchHandle() {
  pagination.value.page = 1;
  getEquipmentList();
}

// 分页大小变化
function sizeChangeHandle(size: number) {
  pagination.value.size = size;
  pagination.value.page = 1;
  getEquipmentList();
}
// 分页当前页变化
function currentChangeHandle(currentPage: number) {
  pagination.value.page = currentPage;
  getEquipmentList();
}

// 获取用户列表
const userList = ref<UserType[]>([]);
const userListLoading = ref(false);
const userListQuery = ref<GetUserListType>({
  page: 1,
  size: 1000,
  name: "",
  ogaCode: "",
});
function getUserList() {
  if (userListLoading.value) return;
  userListLoading.value = true;
  getUserListAPI({
    name: userListQuery.value.name,
    ogaCode: userListQuery.value.ogaCode,
    page: userListQuery.value.page,
    size: userListQuery.value.size,
  })
    .then((res: any) => {
      userList.value = res.content;
    })
    .finally(() => {
      userListLoading.value = false;
    });
}
getUserList();

// 获取设备类型列表
const equipmentTypeList = ref<EquipmentType[]>([]);
const equipmentTypeListLoading = ref(false);
function getEquipmentTypeList() {
  if (equipmentTypeListLoading.value) return;
  equipmentTypeListLoading.value = true;
  typesAPI()
    .then((res: any) => {
      equipmentTypeList.value = res.deviceTypes || [];
    })
    .catch(() => {
      ElMessage.error("获取设备类型列表失败");
    })
    .finally(() => {
      equipmentTypeListLoading.value = false;
    });
}
getEquipmentTypeList();

// 获取组织结构列表
const ogaList = ref<OgaType[]>([]);
const ogaMap = ref<Record<string, string>>({});
const ogaListApiLoading = ref(false);

// 加载组织列表
const loadOgaList = async () => {
  try {
    if (ogaListApiLoading.value) return;
    ogaListApiLoading.value = true;

    const response = await getOgaListAPI();
    const result = response as any as OgaType[];
    if (result) {
      ogaList.value = result || [];
      ogaList.value?.forEach((item) => {
        ogaMap.value[item.code] = item.name;
      });
    }
  } catch (error) {
    ElMessage.error("获取组织列表失败");
    console.error("Load oga list error:", error);
  } finally {
    ogaListApiLoading.value = false;
  }
};
loadOgaList();

// 添加设备
const addDialogVisible = ref(false);
const addFormRef = ref();
const addFormLoading = ref(false);
const addForm = ref<AddOrUpdateEquipmentQueryType>({
  id: "",
  name: "",
  typeId: "",
  code: "",
  model: "",
  chargeUserCode: "",
  status: EquipmentStatus.IDLE,
  location: "",
  belong: "",
  purchaseDate: 0,
  deliveryDate: 0,
  useYears: 0,
  purchasePrice: 0,
  description1: "",
  description2: "",
});

// 添加设备
function addHandle() {
  addDialogVisible.value = true;
  // 等待DOM更新后清除验证状态
  nextTick(() => {
    addFormRef.value?.clearValidate();
  });
}

// 编辑设备
function editHandle(row: EquipmentType) {
  router.push({
    name: "EquipmentDetails",
    query: {
      id: row.id,
    },
  });
}

// 表单验证规则 - 设置为手动触发，避免弹框打开时就显示错误
const addFormRules = {
  name: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
  typeId: [{ required: true, message: "请选择设备类型", trigger: "blur" }],
  code: [{ required: true, message: "请输入设备序列号", trigger: "blur" }],
};

// 重置添加表单
function resetAddForm() {
  addForm.value = {
    id: "",
    name: "",
    typeId: "",
    code: "",
    model: "",
    chargeUserCode: "",
    status: EquipmentStatus.IDLE,
    location: "",
    belong: "",
    purchaseDate: 0,
    deliveryDate: 0,
    useYears: 0,
    purchasePrice: 0,
    description1: "",
    description2: "",
  };
  addFormRef.value?.clearValidate();
}

// 日期验证函数 - 禁用今日之后的日期
const disableFutureDates = (time: Date) => {
  const today = new Date();
  today.setHours(23, 59, 59, 999); // 设置为今日的最后一刻
  return time.getTime() > today.getTime();
};

// 提交添加表单
function submitAddForm() {
  // 防止并发提交
  if (addFormLoading.value) return;

  addFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      addFormLoading.value = true;
      addOrUpdateEquipmentAPI({
        id: addForm.value.id,
        name: addForm.value.name,
        typeId: addForm.value.typeId,
        code: addForm.value.code,
        model: addForm.value.model,
        chargeUserCode: addForm.value.chargeUserCode,
        status: addForm.value.status,
        location: addForm.value.location,
        belong: addForm.value.belong,
        purchaseDate: addForm.value.purchaseDate,
        deliveryDate: addForm.value.deliveryDate,
        useYears: addForm.value.useYears,
        purchasePrice: addForm.value.purchasePrice,
        description1: addForm.value.description1,
        description2: addForm.value.description2,
      })
        .then(() => {
          ElMessage.success(addForm.value.id ? "编辑设备成功" : "添加设备成功");
          addDialogVisible.value = false;
          resetAddForm();
          // 刷新列表
          pagination.value.page = 1;
          getEquipmentList();
        })
        .catch(() => {
          ElMessage.error(addForm.value.id ? "编辑设备失败" : "添加设备失败");
        })
        .finally(() => {
          addFormLoading.value = false;
        });
    }
  });
}

// 删除设备
function deleteHandle(row: any) {
  ElMessageBox.confirm("确定删除该设备吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteEquipmentAPI(row.id)
      .then(() => {
        ElMessage.success("删除设备成功");
        getEquipmentList();
      })
      .catch(() => {
        ElMessage.error("删除设备失败");
      });
  });
}

// 批量导入
function batchImportHandle() {
  batchImportDialogVisible.value = true;
  // 等待DOM更新后清除验证状态
  nextTick(() => {
    batchImportFormRef.value?.clearValidate();
  });
}

// 批量导入相关变量
const batchImportDialogVisible = ref(false);
const batchImportFormRef = ref();
const batchImportLoading = ref(false);
const uploadRef = ref();

const batchImportForm = ref({
  file: null as File | null,
});

const batchImportFormRules = {
  file: [{ required: true, message: "请选择要导入的文件", trigger: "change" }],
};

// 导入进度
const importProgress = ref({
  show: false,
  percentage: 0,
  status: "active" as "active" | "success" | "exception",
  text: "正在导入...",
});

// 导入结果
const importResult = ref({
  show: false,
  successCount: 0,
  failCount: 0,
  failureRecords: [] as Array<{
    rowIndex: number;
    deviceName: string;
    failureReason: string;
  }>,
});

// 文件上传相关函数
function handleFileChange(file: any) {
  batchImportForm.value.file = file.raw;
}

function handleFileRemove() {
  batchImportForm.value.file = null;
}

function beforeFileUpload(file: File) {
  const isExcel =
    file.type ===
      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
    file.type === "application/vnd.ms-excel";
  const isLt100M = file.size / 1024 / 1024 < 100;

  if (!isExcel) {
    ElMessage.error("只能上传 Excel 文件!");
    return false;
  }
  if (!isLt100M) {
    ElMessage.error("文件大小不能超过 100MB!");
    return false;
  }
  return false; // 阻止自动上传
}

// 重置批量导入表单
function resetBatchImportForm() {
  batchImportForm.value.file = null;
  importProgress.value.show = false;
  importResult.value.show = false;
  uploadRef.value?.clearFiles();
}

// 提交批量导入
function submitBatchImport() {
  if (!batchImportForm.value.file) {
    ElMessage.warning("请先选择要导入的文件");
    return;
  }

  batchImportLoading.value = true;
  importProgress.value.show = true;
  importProgress.value.percentage = 0;
  importProgress.value.status = "active";
  importProgress.value.text = "正在上传文件...";
  importResult.value.show = false;

  // 模拟进度
  const progressTimer = setInterval(() => {
    if (importProgress.value.percentage < 90) {
      importProgress.value.percentage += 10;
    }
  }, 200);

  batchImportEquipmentAPI(batchImportForm.value.file)
    .then((response: any) => {
      clearInterval(progressTimer);
      importProgress.value.percentage = 100;
      importProgress.value.status = "success";
      importProgress.value.text = "导入完成";

      importResult.value.show = true;
      importResult.value.successCount = response.successCount || 0;
      importResult.value.failCount = response.failureCount || 0;
      importResult.value.failureRecords = response.failureRecords || [];

      if (importResult.value.successCount > 0) {
        ElMessage.success(
          `成功导入 ${importResult.value.successCount} 条设备信息`
        );
        // 刷新列表
        getEquipmentList();
      }

      if (importResult.value.failCount > 0) {
        ElMessage.warning(
          `有 ${importResult.value.failCount} 条数据导入失败，请查看错误详情`
        );
      }
    })
    .catch((error: any) => {
      clearInterval(progressTimer);
      importProgress.value.status = "exception";
      importProgress.value.text = "导入失败";
      console.error("批量导入失败:", error);
      ElMessage.error("批量导入失败，请稍后重试");
    })
    .finally(() => {
      batchImportLoading.value = false;
    });
}

// 下载模板
function downloadTemplateHandle() {
  // 使用axios直接下载文件
  axios({
    url: "/api/dms/devices/downloadDeviceImportTemplate",
    method: "GET",
    responseType: "blob", // 重要：设置响应类型为blob
    headers: {
      "Content-Type": "application/json",
    },
  })
    .then((response: any) => {
      // 创建blob URL
      const blob = new Blob([response.data], {
        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      });
      const url = window.URL.createObjectURL(blob);

      // 创建下载链接
      const link = document.createElement("a");
      link.href = url;
      link.download = "设备导入模板.xlsx";
      link.style.display = "none";

      // 触发下载
      document.body.appendChild(link);
      link.click();

      // 清理
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);

      ElMessage.success("模板下载成功");
    })
    .catch((error: any) => {
      console.error("下载模板失败:", error);
      ElMessage.error("下载模板失败，请稍后重试");
    });
}

// 更改设备状态
const updateDeviceStatusDialogVisible = ref(false);
const updateDeviceStatusForm = ref({
  deviceId: "",
  status: "",
});
const updateDeviceStatusFormRules = {
  status: [{ required: true, message: "请选择设备状态", trigger: "blur" }],
};
const updateDeviceStatusFormRef = ref();
const updateDeviceStatusFormLoading = ref(false);

function updateDeviceStatusHandle(row: any) {
  updateDeviceStatusDialogVisible.value = true;
  updateDeviceStatusForm.value.deviceId = row.id;
  updateDeviceStatusForm.value.status = row.status;
}
function submitUpdateDeviceStatusForm() {
  if (updateDeviceStatusFormLoading.value) return;
  updateDeviceStatusFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      updateDeviceStatusFormLoading.value = true;
      updateDeviceStatusAPI({
        deviceId: updateDeviceStatusForm.value.deviceId,
        status: updateDeviceStatusForm.value.status,
      })
        .then(() => {
          updateDeviceStatusDialogVisible.value = false;
          updateDeviceStatusFormLoading.value = false;
          ElMessage.success("更改设备状态成功");
          getEquipmentList();
        })
        .catch((error) => {
          ElMessage.error(error.message);
        })
        .finally(() => {
          updateDeviceStatusFormLoading.value = false;
        });
    }
  });
}

// 一键备份
function backupHandle() {
  backupDatabaseAPI()
    .then(() => {
      ElMessage.success("一键备份成功");
    })
    .catch(() => {
      ElMessage.error("一键备份失败");
    });
}
</script>

<style scoped lang="scss">
#EquipmentManagePage {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.title-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  min-height: 2rem;
  padding-left: 1rem;
  color: $color_brand;
  font-size: $font-size-block-title;
}
.title-wrapper::before {
  position: absolute;
  left: 0;
  top: 50%;
  display: block;
  content: "";
  width: 0.5rem;
  height: 0.5rem;
  border-radius: 50%;
  background-color: $color_brand;
  transform: translateY(-50%);
}
.search-wrapper {
  flex-shrink: 0;
  padding: 1.5rem;
  background-color: #fff;
  border-bottom: 1px solid $border-color-primary;
  .content-wrapper {
    position: relative;
    display: flex;
    align-items: center;
    padding-top: 1rem;
    padding-left: 1rem;
  }
  .search-item {
    display: flex;
    align-items: center;
    margin-right: 2rem;
    .item-label {
      width: 8rem;
      padding-left: 1rem;
      text-align: left;
      color: $text-color-regular;
    }
    .item-label:first-child {
      padding-left: 0;
    }
    .item-input {
      width: 20rem;
    }
  }
  .search-btn {
    height: 3rem;
    display: flex;
    align-items: center;
    padding: 0 1.5rem;
    background-color: $color_brand;
    color: #fff;
    border-radius: 0.5rem;
    cursor: pointer;
  }
  .add-btn-wrapper {
    position: absolute;
    right: 1rem;
    top: 1rem;
    display: flex;
    align-items: center;
    .add-btn {
      margin-right: 1rem;
    }
    .batch-import-btn {
      margin-right: 1rem;
    }
    .download-template-btn {
      margin-right: 1rem;
    }
  }
  .add-btn,
  .batch-import-btn,
  .download-template-btn,
  .backup-btn {
    padding: 0.5rem 1.5rem;
    background-color: $color_brand;
    color: #fff;
    border-radius: 0.5rem;
    cursor: pointer;
  }
}
.data-wrapper {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  padding: 1.5rem;
  background-color: #fff;
  .table-wrapper {
    margin-top: 1rem;
    padding-left: 1rem;
    flex: 1;
    min-height: 0;
  }
  .table-btn {
    display: inline-flex;
    align-items: center;
    background-color: $color_brand;
    color: #fff;
    margin-left: 0.5rem;
    padding: 0 1rem;
    border-radius: 0.5rem;
    font-size: $font-size-base-btn-text;
    cursor: pointer;
  }
  .table-btn:first-child {
    margin-left: 0;
  }
  .table-btn:hover {
    text-decoration: underline;
  }
  .signal-status.IDLE {
    color: #999;
  }
  .signal-status.RESERVEING {
    color: $color_warning;
  }
  .signal-status.IN_USE {
    color: $color_success;
  }
  .signal-status.REPAIRING {
    color: $color_danger;
  }
  .signal-status.DAMAGED {
    color: $color_danger;
  }
  .signal-status.SCRAPPED {
    color: $color_danger;
  }
  .equipment-name-wrapper {
    display: flex;
    align-items: center;
    .equipment-photo {
      width: 5rem;
      height: 5rem;
      border-radius: 0.5rem;
      margin-right: 1rem;
    }
    .equipment-info-wrapper {
      display: flex;
      flex-direction: column;
      .equipment-name {
        padding-top: 0.5rem;
        font-size: $font-size-base;
      }
      .equipment-sn {
        font-size: $font-size-tips;
        color: $text-color-secondary;
      }
    }
  }
}

// 分页区域样式
.pagination-wrapper {
  flex-shrink: 0;
}
:deep(.el-input__inner) {
  text-align: left !important;
}

// 批量导入样式
.batch-import-content {
  .import-tips {
    margin-bottom: 1.5rem;
    padding: 1rem;
    background-color: #f5f7fa;
    border-radius: 0.5rem;
    border-left: 4px solid #409eff;

    p {
      margin: 0.5rem 0;
      color: #606266;
      font-size: $font-size-base;

      &:first-child {
        margin-top: 0;
      }

      &:last-child {
        margin-bottom: 0;
      }
    }
  }

  .import-progress {
    margin: 1.5rem 0;

    .progress-text {
      margin-top: 0.5rem;
      text-align: center;
      color: #606266;
      font-size: $font-size-base;
    }
  }

  .import-result {
    margin-top: 1.5rem;
    padding: 1rem;
    background-color: #f5f7fa;
    border-radius: 0.5rem;

    .result-title {
      font-weight: 600;
      color: #303133;
      margin-bottom: 1rem;
    }

    .result-content {
      display: flex;
      gap: 2rem;
      margin-bottom: 1rem;

      .result-item {
        display: flex;
        align-items: center;

        .label {
          font-weight: 500;
          margin-right: 0.5rem;
        }

        .value {
          font-weight: 600;
        }

        &.success .value {
          color: #67c23a;
        }

        &.error .value {
          color: #f56c6c;
        }
      }
    }

    .error-list {
      border-top: 1px solid #dcdfe6;
      padding-top: 1rem;

      .error-title {
        font-weight: 500;
        color: #f56c6c;
        margin-bottom: 0.5rem;
      }

      .error-item {
        display: flex;
        margin-bottom: 0.25rem;
        font-size: $font-size-base;

        .error-row {
          color: #f56c6c;
          font-weight: 500;
          margin-right: 0.5rem;
          width: 6rem;
        }

        .error-name {
          color: #f56c6c;
          font-weight: 500;
          margin-right: 0.5rem;
          width: 10rem;
        }

        .error-message {
          flex: 1;
          color: #606266;
        }
      }
    }
  }
}

// 上传组件样式调整
:deep(.upload-demo) {
  .el-upload-dragger {
    width: 100%;
    height: 120px;
  }

  .el-upload__tip {
    color: #909399;
    font-size: $font-size-base;
  }
}
</style>
